/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package epollserver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;

/**
 *
 * @author Bryce
 */
public class Logger implements Runnable {
    private String fileName;
    private ConcurrentLinkedQueue printQueue;
    public boolean running;
    
    public Logger(String filename) {
        this.fileName = filename;
        printQueue = new ConcurrentLinkedQueue();
        running = true;
    }

    @Override
    public void run() {
        //Are we printing to stdout or file?
        if(this.fileName != null) {
            File file = new File(this.fileName);
            try {
                PrintStream printStream = new PrintStream(new FileOutputStream(file));
                System.setOut(printStream);
            } catch (FileNotFoundException ex) {
                System.out.println("Could not print to file, using stdout instead.");
            }
        }
        while(running) {
            if(!printQueue.isEmpty()) {
                System.out.println(printQueue.poll());
            }
        }
    }
    
    public void addItem(String item) {
        printQueue.add(item);
    }
    
}
